require "import"
import "android.widget.*"
import "android.view.*"
import "os"
import "android.app.AlertDialog"
import "android.widget.PopupMenu"
import "android.content.Intent"
import "android.net.Uri"

-- Lista de feeds RSS do Google Notícias por categoria
local fontesNoticias = {
    {nome = "Brasil Geral", url = "https://news.google.com/rss/search?q=not%C3%ADcias+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"},
    {nome = "Tecnologia", url = "https://news.google.com/rss/search?q=tecnologia+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"},
    {nome = "Política", url = "https://news.google.com/rss/search?q=pol%C3%ADtica+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"},
    {nome = "Esportes", url = "https://news.google.com/rss/search?q=esportes+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"},
    {nome = "Negócios", url = "https://news.google.com/rss/search?q=neg%C3%B3cios+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"},
    {nome = "Entretenimento", url = "https://news.google.com/rss/search?q=entretenimento+brasil&hl=pt-BR&gl=BR&ceid=BR:pt-419"}
}

-- Variáveis para armazenar notícias
local noticias = {}
local indiceAtual = 1
local feedAtual = fontesNoticias[1].url

-- Função para processar e exibir notícias
function exibirNoticia()
    if #noticias == 0 then
        textoResposta.setText("Nenhuma notícia carregada ainda. Aguarde...")
        return
    end
    
    local noticia = noticias[indiceAtual]
    local texto = string.format(
        "📰 Notícia %d de %d:\n\n" ..
        "Título: %s\n" ..
        "Fonte: %s\n" ..
        "Publicado em: %s\n" ..
        "Descrição: %s\n",
        indiceAtual, #noticias,
        noticia.title or "Sem título",
        noticia.fonte or "Desconhecida",
        noticia.pubDate or "Desconhecido",
        noticia.description or "Sem descrição disponível"
    )
    textoResposta.setText(texto)
    botaoAbrirNoticia.setEnabled(true)
    service.speak("Notícia " .. indiceAtual .. " de " .. #noticias .. ": " .. noticia.title)
end

-- Layout da interface
layout = {
    LinearLayout;
    orientation = "vertical";
    layout_width = "match_parent";
    layout_height = "match_parent";
    backgroundColor = "#000000";
    padding = "10dp";
    {
        ScrollView;
        layout_width = "match_parent";
        layout_height = "0dp";
        layout_weight = "1";
        {
            LinearLayout;
            orientation = "vertical";
            layout_width = "match_parent";
            layout_height = "wrap_content";
            {TextView;
                id = "textoResposta";
                layout_width = "match_parent";
                layout_height = "wrap_content";
                text = "Bem-vindo ao aplicativo de notícias. Carregando notícias...",
                textSize = "16sp";
                textColor = "#ffffff";
                padding = "10dp";};
        };
    };
    {
        LinearLayout;
        orientation = "horizontal";
        layout_width = "match_parent";
        layout_height = "wrap_content";
        gravity = "center";
        {
            Button;
            text = "Notícia Anterior";
            id = "botaoAnterior";
            textColor = "#ffffff";
            backgroundColor = "#0066AA";
            layout_width = "wrap_content";
            layout_height = "wrap_content";
            layout_margin = "5dp";
            onClick = function()
                if indiceAtual > 1 then
                    indiceAtual = indiceAtual - 1
                    exibirNoticia()
                else
                    textoResposta.setText("Esta é a primeira notícia!")
                    service.speak("Esta é a primeira notícia!")
                end
            end;
        };
        {
            Button;
            text = "Próxima Notícia";
            id = "botaoProxima";
            textColor = "#ffffff";
            backgroundColor = "#0066AA";
            layout_width = "wrap_content";
            layout_height = "wrap_content";
            layout_margin = "5dp";
            onClick = function()
                if indiceAtual < #noticias then
                    indiceAtual = indiceAtual + 1
                    exibirNoticia()
                else
                    textoResposta.setText("Esta é a última notícia!")
                    service.speak("Esta é a última notícia!")
                end
            end;
        };
    };
    {
        LinearLayout;
        orientation = "horizontal";
        layout_width = "match_parent";
        layout_height = "wrap_content";
        gravity = "center";
        layout_margin = "10dp";
        {
            EditText;
            id = "campoNumeroNoticia";
            hint = "Digite aqui o número da notícia";
            textColor = "#ffffff";
            hintTextColor = "#888888";
            layout_width = "150dp";
            layout_height = "wrap_content";
            inputType = "number";
            textSize = "16sp";
        };
        {
            Button;
            text = "Ir para Notícia";
            textColor = "#ffffff";
            backgroundColor = "#0066AA";
            layout_width = "wrap_content";
            layout_height = "wrap_content";
            layout_marginLeft = "10dp";
            onClick = function()
                local numero = tonumber(campoNumeroNoticia.getText().toString())
                if numero and numero >= 1 and numero <= #noticias then
                    indiceAtual = numero
                    exibirNoticia()
                else
                    textoResposta.setText("Por favor, digite um número válido entre 1 e " .. #noticias)
                    service.speak("Número inválido!")
                end
            end;
        };
    };
    {
        Button;
        id = "botaoFeeds";
        text = "Escolher categoria de notícias";
        textColor = "#ffffff";
        backgroundColor = "#00AA00";
        layout_width = "match_parent";
        layout_height = "wrap_content";
        layout_margin = "10dp";
        onClick = function(view)
            local context = view.getContext()
            local menu = PopupMenu(context, view)
            for i, feed in ipairs(fontesNoticias) do
                menu.getMenu().add(feed.nome)
            end
            menu.setOnMenuItemClickListener({
                onMenuItemClick = function(item)
                    for _, feed in ipairs(fontesNoticias) do
                        if feed.nome == item.getTitle() then
                            feedAtual = feed.url
                            textoResposta.setText("Carregando notícias de " .. feed.nome .. "...")
                            service.speak("Carregando notícias de " .. feed.nome)
                            Http.get(feedAtual, function(status, dados)
                                if status == 200 and dados then
                                    parseRSS(dados, feed.nome)
                                else
                                    textoResposta.setText("Erro ao carregar notícias de " .. feed.nome .. ". Status: " .. tostring(status))
                                    service.speak("Erro ao carregar notícias.")
                                end
                            end)
                            break
                        end
                    end
                    return true
                end
            })
            menu.show()
        end;
    };
    {
        Button;
        id = "botaoAbrirNoticia";
        text = "Abrir e Ouvir Notícia";
        textColor = "#ffffff";
        backgroundColor = "#FF8800";
        layout_width = "match_parent";
        layout_height = "wrap_content";
        layout_margin = "10dp";
        enabled = false;
        onClick = function(view)
            local noticia = noticias[indiceAtual]
            if noticia and noticia.link then
                local intent = Intent(Intent.ACTION_VIEW)
                intent.setData(Uri.parse(noticia.link))
                view.getContext().startActivity(intent)
                service.speak("Abrindo notícia: " .. noticia.title .. ". Aguarde enquanto a página é carregada para ser lida em voz alta.")
                
                -- Atraso de 7 segundos para tentar garantir o carregamento
                task(7000, function()
                    service.speak("Página carregada. Iniciando a leitura em voz alta agora.")
                    if service.click({
                        {"%Toque$100",
                        "Personalizar e controlar o Google Chrome$100",
                        "Ouvir esta página"}
                    }) then
                        service.speak("Lendo a notícia em voz alta.")
                    else
                        service.speak("Não foi possível iniciar a leitura automática. Toque no menu do navegador e selecione Ouvir esta página manualmente.")
                    end
                end)
                
                dlg.dismiss()
            end
        end;
    };
    {
        Button;
        text = "Sair";
        backgroundColor = "#AA0000";
        textColor = "#ffffff";
        layout_width = "wrap_content";
        layout_height = "wrap_content";
        onClick = function()
            dlg.dismiss()
        end;
    };
}

-- Inicialização do diálogo
dlg = LuaDialog()
dlg.setTitle("Notícias do Dia")
local view = loadlayout(layout)
dlg.setView(view)
dlg.show()

-- Função para parsear o RSS manualmente
function parseRSS(rssData, fonteNome)
    noticias = {}
    for item in rssData:gmatch("<item>(.-)</item>") do
        local noticia = {}
        noticia.title = item:match("<title>(.-)</title>") or "Sem título"
        noticia.link = item:match("<link>(.-)</link>") or "Sem link"
        noticia.pubDate = item:match("<pubDate>(.-)</pubDate>") or "Desconhecido"
        noticia.description = item:match("<description>(.-)</description>") or "Sem descrição"
        noticia.fonte = fonteNome
        
        if noticia.description then
            noticia.description = noticia.description:gsub("<!%[CDATA%[", ""):gsub("%]%]", ""):gsub("<[^>]+>", "")
        end
        
        table.insert(noticias, noticia)
    end
    
    if #noticias > 0 then
        indiceAtual = 1
        exibirNoticia()
    else
        textoResposta.setText("Nenhuma notícia encontrada no feed de " .. fonteNome .. ". Verifique o formato do RSS.")
        service.speak("Nenhuma notícia encontrada.")
    end
end

-- Carregar notícias iniciais
service.speak("Bem-vindo ao aplicativo de notícias. Carregando notícias do Brasil...")
Http.get(feedAtual, function(status, dados)
    if status == 200 and dados then
        parseRSS(dados, "Brasil Geral")
    else
        textoResposta.setText("Erro ao carregar notícias iniciais. Status: " .. tostring(status))
        service.speak("Erro ao carregar notícias iniciais.")
    end
end)